// pages/edit-company/edit-company.ts
import { enterpriseCategories, getLevel1Categories } from '../../../config/enterprise-categories';
import { updateEnterprise } from '../../../api/enterprise.js';
import { uploadLicense, uploadCert, uploadAgent, parseFilesJson } from '../../../api/enterprise.js';
import userManager from '../../../utils/userManager.js';

interface OptionItem {
  name: string;
  value: string;
}

interface FormData {
  company_name: string;
  company_type: string;
  funding_stage: string;
  staff_size: string;
  company_nature: string;
  contact_name: string;
  contact_phone: string;
  company_address: string;
  company_description: string;
}

interface CategoryItem {
  path: string;
  level1: string;
  level2: string;
  level3: string;
}

interface EnterpriseCategories {
  [key: string]: {
    [key: string]: string[];
  };
}

Page({
  data: {
    loading: true,
    enterpriseId: 0,
    
    // 表单数据
    formData: {
      company_name: '',
      company_type: '',
      funding_stage: '',
      staff_size: '',
      company_nature: '',
      contact_name: '',
      contact_phone: '',
      company_address: '',
      company_description: ''
    } as FormData,
    
    // 企业类别三层数据结构（从配置文件导入）
    enterpriseCategories: enterpriseCategories as EnterpriseCategories,
    
    // 企业类别选择状态
    selectedCategories: [] as CategoryItem[],
    showCategoryModal: false,
    currentSelection: {
      level1: '',
      level2: '',
      level3: ''
    },
    level1List: [] as string[],
    level2List: [] as string[],
    level3List: [] as string[],
    selectedLevel1: '',
    selectedLevel2: '',
    selectedLevel3: '',
    
    // 新的分类选择状态（参考search-results）
    currentCategoryLevel: 'level1', // level1, level2, level3
    currentCategoryList: [] as string[],
    tempSelectedLevel1: '',
    tempSelectedLevel2: '',
    tempSelectedLevel3: '',
    
    fundingStageList: [
      { name: '请选择融资阶段', value: '' },
      { name: '种子轮', value: 'seed' },
      { name: '天使轮', value: 'angel' },
      { name: 'A轮', value: 'a' },
      { name: 'B轮', value: 'b' },
      { name: 'C轮', value: 'c' },
      { name: 'D轮及以上', value: 'd' },
      { name: '已上市', value: 'ipo' },
      { name: '未融资', value: 'none' }
    ] as OptionItem[],
    fundingStageIndex: 0,
    
    staffSizeList: [
      { name: '请选择人员规模', value: '' },
      { name: '1-10人', value: '1-10' },
      { name: '11-50人', value: '11-50' },
      { name: '51-200人', value: '51-200' },
      { name: '201-500人', value: '201-500' },
      { name: '501-1000人', value: '501-1000' },
      { name: '1000人以上', value: '1000+' }
    ] as OptionItem[],
    staffSizeIndex: 0,
    
    companyNatureList: [
      { name: '请选择公司性质', value: '' },
      { name: '有限责任公司', value: 'limited' },
      { name: '股份有限公司', value: 'joint' },
      { name: '合伙企业', value: 'partnership' },
      { name: '个人独资企业', value: 'individual' },
      { name: '外商投资企业', value: 'foreign' },
      { name: '其他', value: 'other' }
    ] as OptionItem[],
    companyNatureIndex: 0,
    
    // 文件上传
    logoFiles: [] as any[],
    licenseFile: null as any,
    certFile: null as any,
    agentFile: null as any
  },

  onLoad() {
    console.log('编辑企业页面加载完成');
    this.initializeCategories();
    this.loadEnterpriseData();
  },

  // 初始化分类列表
  initializeCategories() {
    const level1List = getLevel1Categories();
    this.setData({
      level1List,
      currentCategoryLevel: 'level1'
    }, () => {
      // 初始化完成后加载一级分类列表
      this.loadCategoryList();
    });
  },

  // 加载企业数据
  async loadEnterpriseData() {
    wx.showLoading({ title: '加载中...' });
    
    try {
      // ✅ 从用户信息缓存中获取企业数据（不单独请求接口）
      const userData = await userManager.getUserInfo(false, false);
      console.log('从缓存获取用户信息（含企业）:', userData);
      
      if (userData && (userData as any).enterprise) {
        const enterpriseData = (userData as any).enterprise;
        
        // 解析企业类别
        const selectedCategories = this.parseEnterpriseCategories(enterpriseData.tags);
        
        // 找到对应的选择器索引
        const fundingStageIndex = this.findOptionIndex(this.data.fundingStageList, enterpriseData.funding_stage);
        const staffSizeIndex = this.findOptionIndex(this.data.staffSizeList, enterpriseData.staff_size);
        const companyNatureIndex = this.findOptionIndex(this.data.companyNatureList, enterpriseData.nature);
        
        // 解析文件
        const logoFiles = this.parseLogoFiles(enterpriseData.logo_files);
        const licenseFile = this.parseFile(enterpriseData.license_file, '营业执照');
        const certFile = this.parseFile(enterpriseData.cert_file, 'ISO认证证书');
        const agentFile = this.parseFile(enterpriseData.agent_file, '其他资质证书');
        
        this.setData({
          enterpriseId: enterpriseData.id,
          formData: {
            company_name: enterpriseData.company_name || enterpriseData.name || '',
            company_type: Array.isArray(enterpriseData.tags) ? enterpriseData.tags.join(',') : (enterpriseData.tags || ''),
            funding_stage: enterpriseData.funding_stage || '',
            staff_size: enterpriseData.staff_size || '',
            company_nature: enterpriseData.nature || '',
            contact_name: enterpriseData.contact_name || '',
            contact_phone: enterpriseData.contact_phone || '',
            company_address: enterpriseData.address || '',
            company_description: enterpriseData.description || ''
          },
          selectedCategories,
          fundingStageIndex,
          staffSizeIndex,
          companyNatureIndex,
          logoFiles,
          licenseFile,
          certFile,
          agentFile,
          loading: false
        });
      } else {
        wx.showToast({
          title: '获取企业信息失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error: any) {
      console.error('加载企业信息失败:', error);
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '加载失败'),
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } finally {
      wx.hideLoading();
    }
  },

  // 解析企业类别
  parseEnterpriseCategories(tags: string | string[]): CategoryItem[] {
    if (!tags) return [];
    
    // 如果tags是数组，直接使用；如果是字符串，按逗号分割
    const categoryArray = Array.isArray(tags) ? tags : tags.split(',');
    
    return categoryArray.map(tag => ({
      path: String(tag).trim(),
      level1: String(tag).trim(),
      level2: '',
      level3: ''
    })).filter(item => item.level1);
  },

  // 查找选项索引
  findOptionIndex(options: OptionItem[], value: string): number {
    const index = options.findIndex(option => option.value === value);
    return index >= 0 ? index : 0;
  },

  // 辅助函数：规范化文件数据（处理数组或JSON字符串）
  normalizeFileData(fileData: any): string[] {
    // 如果为空或无效值
    if (!fileData || fileData === 'undefined' || fileData === 'null') {
      return [];
    }
    
    // 如果已经是数组，直接返回
    if (Array.isArray(fileData)) {
      return fileData.filter(url => url && typeof url === 'string');
    }
    
    // 如果是字符串，尝试解析
    if (typeof fileData === 'string') {
      try {
        return parseFilesJson(fileData);
      } catch (error) {
        console.error('解析文件数据失败:', error);
        return [];
      }
    }
    
    return [];
  },

  // 解析Logo文件
  parseLogoFiles(logoFilesData: any): any[] {
    const files = this.normalizeFileData(logoFilesData);
    console.log('解析Logo文件:', logoFilesData, '=> 结果:', files);
    return files.map((url: string, index: number) => ({
      url,
      path: url,
      name: `logo_${index + 1}`,
      size: 0
    }));
  },

  // 解析单个文件
  parseFile(fileData: any, name: string): any {
    const files = this.normalizeFileData(fileData);
    console.log(`解析${name}:`, fileData, '=> 结果:', files);
    if (files.length > 0) {
      return {
        path: files[0],
        url: files[0],
        name
      };
    }
    return null;
  },

  // 输入事件处理
  onCompanyNameInput(e: any) {
    this.setData({
      'formData.company_name': e.detail.value
    });
  },

  onContactNameInput(e: any) {
    this.setData({
      'formData.contact_name': e.detail.value
    });
  },

  onContactPhoneInput(e: any) {
    this.setData({
      'formData.contact_phone': e.detail.value
    });
  },

  onCompanyAddressInput(e: any) {
    this.setData({
      'formData.company_address': e.detail.value
    });
  },

  onCompanyDescriptionInput(e: any) {
    this.setData({
      'formData.company_description': e.detail.value
    });
  },

  // 选择器变化事件
  onFundingStageChange(e: any) {
    const index = e.detail.value;
    const item = this.data.fundingStageList[index];
    this.setData({
      fundingStageIndex: index,
      'formData.funding_stage': item.value
    });
  },

  onStaffSizeChange(e: any) {
    const index = e.detail.value;
    const item = this.data.staffSizeList[index];
    this.setData({
      staffSizeIndex: index,
      'formData.staff_size': item.value
    });
  },

  onCompanyNatureChange(e: any) {
    const index = e.detail.value;
    const item = this.data.companyNatureList[index];
    this.setData({
      companyNatureIndex: index,
      'formData.company_nature': item.value
    });
  },

  // 企业类别选择（参考search-results的逻辑）
  showCategorySelector() {
    if (this.data.selectedCategories.length >= 5) {
      wx.showToast({
        title: '最多只能选择5个企业类别',
        icon: 'none'
      });
      return;
    }
    
    this.setData({
      showCategoryModal: true,
      currentCategoryLevel: 'level1',
      currentCategoryList: this.data.level1List,
      tempSelectedLevel1: '',
      tempSelectedLevel2: '',
      tempSelectedLevel3: ''
    });
  },

  hideCategorySelector() {
    this.setData({
      showCategoryModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 切换分类级别
  switchCategoryLevel(e: any) {
    const level = e.currentTarget.dataset.level;
    this.setData({
      currentCategoryLevel: level
    });
    this.loadCategoryList();
  },

  // 加载分类列表
  loadCategoryList() {
    const { currentCategoryLevel, tempSelectedLevel1, tempSelectedLevel2, enterpriseCategories } = this.data;
    let categoryList: string[] = [];

    if (currentCategoryLevel === 'level1') {
      // 一级：主要类别
      categoryList = this.data.level1List;
    } else if (currentCategoryLevel === 'level2' && tempSelectedLevel1) {
      // 二级：子类别
      categoryList = Object.keys(enterpriseCategories[tempSelectedLevel1] || {});
    } else if (currentCategoryLevel === 'level3' && tempSelectedLevel1 && tempSelectedLevel2) {
      // 三级：具体类别
      categoryList = enterpriseCategories[tempSelectedLevel1]?.[tempSelectedLevel2] || [];
    }

    this.setData({
      currentCategoryList: categoryList
    });
  },

  // 从分类弹窗中选择主要类别
  selectLevel1FromCategory(e: any) {
    const level1 = e.currentTarget.dataset.category;
    
    this.setData({
      tempSelectedLevel1: level1,
      tempSelectedLevel2: '',
      tempSelectedLevel3: '',
      currentCategoryLevel: 'level2'
    }, () => {
      // 在数据更新后加载二级分类列表
      this.loadCategoryList();
    });
  },

  // 从分类弹窗中选择子类别
  selectLevel2FromCategory(e: any) {
    const level2 = e.currentTarget.dataset.category;
    
    this.setData({
      tempSelectedLevel2: level2,
      tempSelectedLevel3: ''
    }, () => {
      // 检查是否有三级分类，如果有则切换到三级，否则直接确认选择
      const { tempSelectedLevel1, enterpriseCategories } = this.data;
      const level3List = enterpriseCategories[tempSelectedLevel1]?.[level2] || [];
      
      if (level3List.length > 0) {
        this.setData({
          currentCategoryLevel: 'level3'
        }, () => {
          this.loadCategoryList();
        });
      } else {
        // 如果没有三级分类，直接确认选择
        this.confirmCategorySelection();
      }
    });
  },

  // 从分类弹窗中选择具体类别
  selectLevel3FromCategory(e: any) {
    const level3 = e.currentTarget.dataset.category;
    
    this.setData({
      tempSelectedLevel3: level3
    });
    
    // 选择三级分类后直接确认
    this.confirmCategorySelection();
  },


  // 清除分类筛选
  clearCategoryFilter() {
    this.setData({
      tempSelectedLevel1: '',
      tempSelectedLevel2: '',
      tempSelectedLevel3: '',
      currentCategoryLevel: 'level1'
    });
    this.loadCategoryList();
  },

  // 保留原有的方法（向后兼容）
  selectLevel1(e: any) {
    const level1 = e.currentTarget.dataset.category;
    const level2List = Object.keys(this.data.enterpriseCategories[level1] || {});
    
    this.setData({
      selectedLevel1: level1,
      selectedLevel2: '',
      selectedLevel3: '',
      'currentSelection.level1': level1,
      'currentSelection.level2': '',
      'currentSelection.level3': '',
      level2List,
      level3List: []
    });
  },

  selectLevel2(e: any) {
    const level2 = e.currentTarget.dataset.category;
    const { selectedLevel1, enterpriseCategories } = this.data;
    const level3List = enterpriseCategories[selectedLevel1]?.[level2] || [];
    
    this.setData({
      selectedLevel2: level2,
      selectedLevel3: '',
      'currentSelection.level2': level2,
      'currentSelection.level3': '',
      level3List
    });
  },

  selectLevel3(e: any) {
    const level3 = e.currentTarget.dataset.category;
    
    this.setData({
      selectedLevel3: level3,
      'currentSelection.level3': level3
    });
  },

  confirmCategorySelection() {
    const { tempSelectedLevel1, tempSelectedLevel2, tempSelectedLevel3, selectedCategories } = this.data;
    
    if (!tempSelectedLevel1) {
      wx.showToast({
        title: '请选择类别',
        icon: 'none'
      });
      return;
    }
    
    let categoryPath = tempSelectedLevel1;
    if (tempSelectedLevel2) {
      categoryPath += ` > ${tempSelectedLevel2}`;
      if (tempSelectedLevel3) {
        categoryPath += ` > ${tempSelectedLevel3}`;
      }
    }
    
    if (selectedCategories.some(cat => cat.path === categoryPath)) {
      wx.showToast({
        title: '该类别已选择',
        icon: 'none'
      });
      return;
    }
    
    const newCategories = [...selectedCategories, {
      path: categoryPath,
      level1: tempSelectedLevel1,
      level2: tempSelectedLevel2,
      level3: tempSelectedLevel3
    }];
    
    const categoryTypes = newCategories.map(cat => cat.level3 || cat.level2 || cat.level1);
    
    this.setData({
      selectedCategories: newCategories,
      'formData.company_type': categoryTypes.join(',')
    });
    
    this.hideCategorySelector();
  },

  removeCategory(e: any) {
    const index = e.currentTarget.dataset.index;
    const { selectedCategories } = this.data;
    const newCategories = selectedCategories.filter((_, i) => i !== index);
    
    const categoryTypes = newCategories.map(cat => cat.level3 || cat.level2 || cat.level1);
    
    this.setData({
      selectedCategories: newCategories,
      'formData.company_type': categoryTypes.join(',')
    });
  },

  // 文件上传处理
  onLogoUploadSuccess(e: any) {
    const { allImages } = e.detail;
    console.log('Logo上传成功:', allImages);
    
    this.setData({
      logoFiles: allImages.map((img: any) => ({
        url: img.url,
        path: img.url,
        name: img.name || 'logo',
        size: img.size
      }))
    });
  },

  onLogoRemove(e: any) {
    const { remainingImages } = e.detail;
    console.log('删除Logo后剩余:', remainingImages);
    
    this.setData({
      logoFiles: remainingImages.map((img: any) => ({
        url: img.url,
        path: img.url,
        name: img.name || 'logo',
        size: img.size
      }))
    });
  },

  // 提交表单
  async submitForm() {
    if (!this.validateForm()) {
      return;
    }
    
    wx.showLoading({ title: '保存中...' });
    
    try {
      const submitData: any = {
        name: this.data.formData.company_name,
        contact_name: this.data.formData.contact_name,
        contact_phone: this.data.formData.contact_phone,
        tags: this.data.formData.company_type,
        funding_stage: this.data.formData.funding_stage,
        staff_size: this.data.formData.staff_size,
        nature: this.data.formData.company_nature,
        address: this.data.formData.company_address,
        description: this.data.formData.company_description
      };
      
      // 添加Logo文件
      if (this.data.logoFiles.length > 0) {
        submitData.logo_files = JSON.stringify(
          this.data.logoFiles.map(file => file.url).filter(url => url)
        );
      }
      
      // 添加营业执照
      if (this.data.licenseFile && this.data.licenseFile.url) {
        submitData.license_file = JSON.stringify([this.data.licenseFile.url]);
      }
      
      // 添加ISO认证证书
      if (this.data.certFile && this.data.certFile.url) {
        submitData.cert_file = JSON.stringify([this.data.certFile.url]);
      }
      
      // 添加其他资质证书
      if (this.data.agentFile && this.data.agentFile.url) {
        submitData.agent_file = JSON.stringify([this.data.agentFile.url]);
      }
      
      const result = await updateEnterprise(this.data.enterpriseId, submitData);
      
      wx.hideLoading();
      
      if (result.status === 200 || result.code === 200) {
        // ✅ 企业信息更新成功，刷新用户信息缓存（包含企业数据）
        await userManager.refreshAfterUpdate('企业信息更新');
        
        wx.showToast({
          title: '修改成功，等待审核',
          icon: 'success',
          duration: 2000
        });
        
        setTimeout(() => {
          // 返回上一页，上一页会自动从缓存获取最新的企业数据
          wx.navigateBack();
        }, 2000);
      } else {
        wx.showToast({
          title: result.msg || '修改失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('修改企业失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '修改失败，请重试'),
        icon: 'none'
      });
    }
  },

  // 表单验证
  validateForm(): boolean {
    const { formData } = this.data;
    
    if (!formData.company_name.trim()) {
      wx.showToast({
        title: '请输入企业全称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.company_type.trim()) {
      wx.showToast({
        title: '请选择企业类别',
        icon: 'none'
      });
      return false;
    }
    
    // 验证融资阶段
    if (!formData.funding_stage.trim()) {
      wx.showToast({
        title: '请选择融资阶段',
        icon: 'none'
      });
      return false;
    }
    
    // 验证人员规模
    if (!formData.staff_size.trim()) {
      wx.showToast({
        title: '请选择人员规模',
        icon: 'none'
      });
      return false;
    }
    
    // 验证公司性质
    if (!formData.company_nature.trim()) {
      wx.showToast({
        title: '请选择公司性质',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }
    
    const phonePattern = /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/;
    if (!phonePattern.test(formData.contact_phone.trim())) {
      wx.showToast({
        title: '请输入有效的手机号码或固定电话',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    
    return true;
  },

  // 上传营业执照
  async uploadLicense() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }) as any;
      
      const filePath = res.tempFilePaths[0];
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadResult = await uploadLicense(filePath, () => {});
      
      wx.hideLoading();
      
      if (uploadResult.status === 200 || uploadResult.code === 200) {
        this.setData({
          licenseFile: {
            path: filePath,
            url: uploadResult.data.url,
            name: '营业执照'
          }
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传营业执照失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '上传失败'),
        icon: 'none'
      });
    }
  },

  // 上传ISO认证证书
  async uploadCert() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }) as any;
      
      const filePath = res.tempFilePaths[0];
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadResult = await uploadCert(filePath, () => {});
      
      wx.hideLoading();
      
      if (uploadResult.status === 200 || uploadResult.code === 200) {
        this.setData({
          certFile: {
            path: filePath,
            url: uploadResult.data.url,
            name: 'ISO认证证书'
          }
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传ISO认证证书失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '上传失败'),
        icon: 'none'
      });
    }
  },
  
  // 上传其他资质证书
  async uploadAgent() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      }) as any;
      
      const filePath = res.tempFilePaths[0];
      
      wx.showLoading({ title: '上传中...' });
      
      const uploadResult = await uploadAgent(filePath, () => {});
      
      wx.hideLoading();
      
      if (uploadResult.status === 200 || uploadResult.code === 200) {
        this.setData({
          agentFile: {
            path: filePath,
            url: uploadResult.data.url,
            name: '其他资质证书'
          }
        });
        wx.showToast({
          title: '上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传其他资质证书失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '上传失败'),
        icon: 'none'
      });
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 显示帮助
  showHelp() {
    wx.showModal({
      title: '编辑企业帮助',
      content: '编辑企业信息后需重新审核，审核通过后生效。所有字段均可编辑更新。',
      showCancel: false,
      confirmText: '我知道了'
    });
  }
});